<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理设置 - 王掌柜黄金</title>
    <style>
        body {
            background-color: #1E1E1E;
            color: gold;
            font-family: "Microsoft YaHei", sans-serif;
            padding: 20px;
        }
        .container {
            max-width: 400px;
            margin: 0 auto;
        }
        .login-form, .admin-panel {
            background: #333;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }
        .login-form h2, .admin-panel h2 {
            text-align: center;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid gold;
            background: #1E1E1E;
            color: gold;
            border-radius: 4px;
        }
        button {
            width: 100%;
            padding: 10px;
            background: gold;
            color: #1E1E1E;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
        }
        button:hover {
            background: #ffcc00;
        }
        .error-message {
            color: red;
            text-align: center;
            margin-top: 10px;
        }
        .nav-buttons {
            margin-bottom: 20px;
        }
        .nav-buttons button {
            margin-bottom: 10px;
        }
        .subpage {
            display: none;
        }
        .subpage.active {
            display: block;
        }
        .back-btn {
            margin-top: 20px;
        }
        .setting-group {
            margin-bottom: 15px;
            padding: 10px;
            border: 1px solid #555;
            border-radius: 4px;
        }
        .setting-group label {
            display: block;
            margin-bottom: 5px;
        }
        .setting-group input, .setting-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid gold;
            background: #1E1E1E;
            color: gold;
            border-radius: 4px;
        }
        .status {
            text-align: center;
            margin-top: 10px;
            color: #ccc;
        }
        // ... existing code ...
           .qr-upload-group {
               margin-bottom: 15px;
               padding: 10px;
               border: 1px solid #555;
               border-radius: 4px;
           }
        .qr-upload-group label {
            display: block;
            margin-bottom: 5px;
        }
        .qr-preview {
            margin-top: 10px;
            text-align: center;
        }
        .qr-preview img {
            max-width: 150px;
            max-height: 150px;
            border: 1px solid gold;
            border-radius: 4px;
        }
        .upload-btn {
            background: #555;
            color: gold;
            border: 1px solid gold;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            display: inline-block;
            margin-top: 5px;
        }
        .upload-btn:hover {
            background: #666;
        }
        #qrCodeFile {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 登录表单 -->
        <div id="loginForm" class="login-form">
            <h2>管理员登录</h2>
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username" placeholder="输入用户名">
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password"  name="password" placeholder="输入密码">
            </div>
            <div class="row m-t form-group" th:if="${captchaEnabled==true}">
                <label for="password">验证码</label>
                <div class="col-xs-6">
                    <input type="text" name="validateCode" class="form-control code" placeholder="验证码" maxlength="5" />
                </div>
                <div class="col-xs-6" style="width: 50%">
                    <a href="javascript:void(0);" title="点击更换验证码">
                        <img th:src="@{/captcha/captchaImage(type=${captchaType})}" class="imgcode" width="85%"/>
                    </a>
                </div>
            </div>
            <button onclick="loginAdmin()">登录</button>
            <div id="errorMessage" class="error-message"></div>
        </div>

        <!-- 管理面板 -->
        <div id="adminPanel" class="admin-panel" style="display: none;">
            <h2>管理设置</h2>

            <div class="nav-buttons">
                <button onclick="showSubpage('general')">基本设置</button>
                <button onclick="showSubpage('price')">价格设置</button>
                <button onclick="logout()">退出登录</button>
            </div>

            <!-- 基本设置子页面 -->
            <div id="generalSettings" class="subpage">
                <h3>基本设置</h3>
                <div class="setting-group">
                    <label for="shopName">店铺名称</label>
                    <input type="text" id="shopName" value="王掌柜黄金">
                </div>
                <div class="setting-group">
                    <label for="contactPhone">联系电话</label>
                    <input type="text" id="contactPhone" value="18031350654">
                </div>
                <div class="setting-group">
                    <label for="address">店铺地址</label>
                    <input type="text" id="address" value="张家口市纬二路凯地尚都底商王掌柜寄售行">
                </div>

                <!-- 新增二维码上传部分 -->
                <div class="qr-upload-group">
                    <label>二维码图片上传</label>
                    <div class="upload-btn" onclick="document.getElementById('qrCodeFile').click()">
                        选择二维码图片
                    </div>
                    <input type="file" id="qrCodeFile" accept="image/*" onchange="handleQrCodeUpload(this)">
                    <div class="qr-preview" id="qrPreview">
                        <p>暂无预览</p>
                    </div>
                </div>

                <button onclick="saveGeneralSettings()">保存设置</button>
                <button class="back-btn" onclick="showSubpage('')">返回</button>
            </div>
            <!-- 价格设置子页面 -->
            <div id="priceSettings" class="subpage">
                <h3>价格设置</h3>
                <div class="setting-group">
                    <label>黄金加价 (元/克)</label>
                    <input type="number" id="goldMarkup" value="0">
                </div>

                <div class="setting-group">
                    <label>18K金加价 (元/克)</label>
                    <input type="number" id="k18Markup" value="0">
                </div>

                <div class="setting-group">
                    <label>铂金加价 (元/克)</label>
                    <input type="number" id="ptMarkup" value="0">
                </div>

                <div class="setting-group">
                    <label>钯金加价 (元/克)</label>
                    <input type="number" id="pdMarkup" value="0">
                </div>

                <div class="setting-group">
                    <label>白银加价 (元/克)</label>
                    <input type="number" id="agMarkup" value="0">
                </div>

                <button onclick="savePriceSettings()">保存设置</button>
                <button class="back-btn" onclick="showSubpage('')">返回</button>
            </div>
            
            <div id="statusMessage" class="status"></div>
        </div>
    </div>
    <script th:inline="javascript"> var ctx = [[@{/}]]; var captchaType = [[${captchaType}]]; var captchaEnabled = [[${captchaEnabled}]];</script>
    <!--[if lte IE 8]><script>window.location.href=ctx+'html/ie.html';</script><![endif]-->
    <!-- 全局js -->
    <script src="../static/js/jquery.min.js" th:src="@{/js/jquery.min.js}"></script>
    <script src="../static/ajax/libs/validate/jquery.validate.min.js" th:src="@{/ajax/libs/validate/jquery.validate.min.js}"></script>
    <script src="../static/ajax/libs/layer/layer.min.js" th:src="@{/ajax/libs/layer/layer.min.js}"></script>
    <script src="../static/ajax/libs/blockUI/jquery.blockUI.js" th:src="@{/ajax/libs/blockUI/jquery.blockUI.js}"></script>
    <script src="../static/ruoyi/js/ry-ui.js" th:src="@{/ruoyi/js/ry-ui.js?v=4.8.1}"></script>
    <script src="../static/ruoyi/login.js" th:src="@{/ruoyi/login.js}"></script>
    <script>

       $(function () {
           showSubpage("general");
           // 默认显示登录页面，而不是基本设置页面
           document.getElementById('loginForm').style.display = 'block';
           document.getElementById('adminPanel').style.display = 'none';
       })
        // 存储当前活动子页面
        let activeSubpage = '';
        let userNameAll = '';
        // 检查用户是否已登录
        function checkLogin() {
            const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
            if (isLoggedIn) {
                document.getElementById('loginForm').style.display = 'none';
                document.getElementById('adminPanel').style.display = 'block';
                showSubpage(''); // 显示导航按钮
            } else {
                document.getElementById('loginForm').style.display = 'block';
                document.getElementById('adminPanel').style.display = 'none';
            }
        }
        
        // 登录函数
        function loginAdmin() {
            var username = $.common.trim($("input[name='username']").val());
            var password = $.common.trim($("input[name='password']").val());
            var validateCode = $("input[name='validateCode']").val();
            var rememberMe = $("input[name='rememberme']").is(':checked');
            if($.common.isEmpty(validateCode) && captchaEnabled) {
                $.modal.msg("请输入验证码");
                return false;
            }
            $.ajax({
                type: "post",
                url: ctx + "login",
                data: {
                    "username": username,
                    "password": password,
                    "validateCode": validateCode,
                    "rememberMe": rememberMe
                },
                beforeSend: function () {
                    $.modal.loading($("#btnSubmit").data("loading"));
                },
                success: function(r) {
                    if (r.code == web_status.SUCCESS) {
                        localStorage.setItem('isLoggedIn', 'true');
                        document.getElementById('errorMessage').textContent = '';
                        checkLogin();
                        userNameAll = username;
                    } else {
                        $('.imgcode').click();
                        $(".code").val("");
                        $.modal.msg(r.msg);
                    }
                    $.modal.closeLoading();
                }
            });
        }

        // 登出函数
        function logout() {
            localStorage.removeItem('isLoggedIn');
            checkLogin();
        }
        
        // 显示子页面
        function showSubpage(subpage) {
            // 隐藏所有子页面
            document.querySelectorAll('.subpage').forEach(page => {
                page.classList.remove('active');
            });
            
            // 如果指定了子页面，则显示它
            if (subpage) {
                document.getElementById(`${subpage}Settings`).classList.add('active');
                activeSubpage = subpage;
                // 如果是价格设置页面，查询后端价格并回显
                if (subpage === 'price' && userNameAll) {
                    fetch('/app/getOne',{
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            userId: userNameAll
                        })
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.code === 0 && data.data) {
                                // 回显价格数据到表单
                                if (data.data.gold) document.getElementById('goldMarkup').value = data.data.gold;
                                if (data.data.k18) document.getElementById('k18Markup').value = data.data.k18;
                                if (data.data.pt) document.getElementById('ptMarkup').value = data.data.pt;
                                if (data.data.pd) document.getElementById('pdMarkup').value = data.data.pd;
                                if (data.data.ag) document.getElementById('agMarkup').value = data.data.ag;
                            }
                        })
                        .catch(error => {
                            console.error('获取价格数据失败:', error);
                        });
                }
            } else {
                activeSubpage = '';
            }
        }
       let qrCodeFileName = ''; // 存储上传的二维码文件名

       // 处理二维码上传
       function handleQrCodeUpload(input) {
           const file = input.files[0];
           if (!file) return;

           // 验证文件类型
           if (!file.type.startsWith('image/')) {
               alert('请选择图片文件');
               return;
           }

           // 验证文件大小（限制为2MB）
           if (file.size > 10 * 1024 * 1024) {
               alert('图片大小不能超过2MB');
               return;
           }

           // 显示预览
           const reader = new FileReader();
           reader.onload = function(e) {
               const preview = document.getElementById('qrPreview');
               preview.innerHTML = `<img src="${e.target.result}" alt="二维码预览">`;
           };
           reader.readAsDataURL(file);

           // 立即上传文件
           uploadQrCodeFile(file);
       }

       // 上传二维码文件到服务器
       function uploadQrCodeFile(file) {
           const formData = new FormData();
           formData.append('file', file);

           fetch('/common/upload', {
               method: 'POST',
               body: formData
           })
               .then(response => response.json())
               .then(data => {
                   if (data.code === 0) {
                       qrCodeFileName = data.fileName;
                       document.getElementById('statusMessage').textContent = '二维码上传成功';
                       setTimeout(() => {
                           document.getElementById('statusMessage').textContent = '';
                       }, 2000);
                   } else {
                       alert('上传失败: ' + data.msg);
                   }
               })
               .catch(error => {
                   console.error('上传错误:', error);
                   alert('上传失败，请重试');
               });
       }

       // 保存基本设置
        function savePriceSettings() {
            const goldMarkup = document.getElementById('goldMarkup').value;
            const k18Markup = document.getElementById('k18Markup').value;
            const ptMarkup = document.getElementById('ptMarkup').value;
            const pdMarkup = document.getElementById('pdMarkup').value;
            const agMarkup = document.getElementById('agMarkup').value;
            if (userNameAll == null || userNameAll == ''){
                logout()
            }
            var bodyStr = JSON.stringify({
                userId:userNameAll,
                gold:goldMarkup,
                k18:k18Markup,
                pt:ptMarkup,
                pd:pdMarkup,
                ag:agMarkup,
            });
            console.log(bodyStr);
            // 使用fetch发起GET请求（也可使用axios等库）
            fetch('/app/add',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: bodyStr
            }) // 注意：此处URL需与后端一致
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0){
                        document.getElementById('statusMessage').textContent = '保存成功';
                    }
                 });
            // // 模拟保存到服务器
            // setTimeout(() => {
            //     document.getElementById('statusMessage').textContent = '设置已保存';
            //     setTimeout(() => {
            //         document.getElementById('statusMessage').textContent = '';
            //     }, 2000);
            // }, 500);
        }
        
        // // 保存基础数据
       function saveGeneralSettings() {
           const shopname = document.getElementById('shopName').value;
           const phone = document.getElementById('contactPhone').value;
           const address = document.getElementById('address').value;

           if (userNameAll == null || userNameAll == ''){
               logout();
               return;
           }

           // 构建请求数据，包含二维码文件名
           const requestData = {
               userId: userNameAll,
               shopname: shopname,
               phone: phone,
               address: address
           };

           // 如果有上传的二维码文件，添加到请求数据中
           if (qrCodeFileName) {
               requestData.qrCode = qrCodeFileName;
           }

           console.log(JSON.stringify(requestData));

           // 发送请求到后端
           fetch('/app/add', {
               method: 'POST',
               headers: {
                   'Content-Type': 'application/json'
               },
               body: JSON.stringify(requestData)
           })
               .then(response => response.json())
               .then(data => {
                   if (data.code === 0){
                       document.getElementById('statusMessage').textContent = '保存成功';
                       // 清空二维码文件名，避免重复上传
                       qrCodeFileName = '';
                   } else {
                       document.getElementById('statusMessage').textContent = '保存失败: ' + data.msg;
                   }
                   setTimeout(() => {
                       document.getElementById('statusMessage').textContent = '';
                   }, 2000);
               })
               .catch(error => {
                   console.error('保存失败:', error);
                   document.getElementById('statusMessage').textContent = '保存失败，请重试';
                   setTimeout(() => {
                       document.getElementById('statusMessage').textContent = '';
                   }, 2000);
               });
       }


       // 添加用户
        function addUser() {
            const newUsername = document.getElementById('newUsername').value;
            const newPassword = document.getElementById('newPassword').value;
            
            if (!newUsername || !newPassword) {
                document.getElementById('statusMessage').textContent = '用户名和密码不能为空';
                setTimeout(() => {
                    document.getElementById('statusMessage').textContent = '';
                }, 2000);
                return;
            }
            
            // 模拟添加用户
            setTimeout(() => {
                document.getElementById('userList').innerHTML += `<li>${newUsername}</li>`;
                document.getElementById('newUsername').value = '';
                document.getElementById('newPassword').value = '';
                document.getElementById('statusMessage').textContent = '用户已添加';
                setTimeout(() => {
                    document.getElementById('statusMessage').textContent = '';
                }, 2000);
            }, 500);
        }
        
        // 页面加载时检查登录状态
        document.addEventListener('DOMContentLoaded', checkLogin);
    </script>
</body>
</html>